package com.xpc.rpc.loadbalancer.round;

import com.xpc.rpc.annotation.SPIClass;
import com.xpc.rpc.loadbalancer.api.ServiceLoadBalancerApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@SPIClass
public class RoundLoadbalancer<T> implements ServiceLoadBalancerApi<T> {


    private static final Logger LOGGER = LoggerFactory.getLogger(RoundLoadbalancer.class);

    private volatile AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public T select(List<T> services) {
        LOGGER.info("这是轮询负载均衡策略................");
        if(services == null || services.isEmpty()) {
            return null;
        }
        int count = services.size();
        int index = atomicInteger.incrementAndGet();
        if(index >= (Integer.MAX_VALUE-10000)) {
            atomicInteger.set(0);
        }
        return services.get(index % count);
    }
}
